package com.spark.gaea.security.realm;

import com.google.common.base.Strings;
import com.spark.gaea.security.backend.SecurityBackend;
import com.spark.gaea.security.domain.SecurityUser;
import com.spark.gaea.security.utils.SessionUtil;
import com.spark.gaea.utils.exception.GaeaAuthenticationException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

public class GaeaRealm extends AuthorizingRealm {
	private static final Logger LOG;
	@Autowired
	private SecurityBackend securityBackend;
	@Autowired
	Environment env;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
		final String misId = this.env.getProperty("misid");
		final String username = (String) principals.getPrimaryPrincipal();
		final String userId = this.securityBackend.getUserId(username);
		final SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(this.securityBackend.getUserRoles(userId));
		if (Strings.isNullOrEmpty(misId)) {
			authorizationInfo.setStringPermissions(this.securityBackend.getUserPermissions(userId));
		} else {
			authorizationInfo.setStringPermissions(this.securityBackend.getUserPermissionsByMisid(userId, misId));
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
			throws AuthenticationException {
		final UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		final String username = upToken.getUsername();
		final SecurityUser user = this.securityBackend.getUser(username);
		if (user == null) {
			GaeaRealm.LOG.debug("\u7528\u6237[" + username + "]\u4e0d\u5b58\u5728\uff01");
			throw new UnknownAccountException();
		}
		if (user.getRemoved() != null) {
			GaeaRealm.LOG.debug("\u7528\u6237[" + username + "]\u5df2\u9501\u5b9a\uff01");
			throw new LockedAccountException();
		}
		if (user.getEnabled() != 1) {
			GaeaRealm.LOG.debug("\u7528\u6237[" + username + "]\u5df2\u7981\u7528\uff01");
			throw new GaeaAuthenticationException("\u7528\u6237[" + username + "]\u5df2\u7981\u7528");
		}
		SessionUtil.set("userId", user.getId());
		SessionUtil.set("user", user);
		return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), this.getName());
	}

	static {
		LOG = LoggerFactory.getLogger(GaeaRealm.class);
	}
}
